import colorsys
from PIL import Image
import os
import cv2 as cv
import matplotlib as mpl
mpl.use('tkagg')
import matplotlib.pyplot as plt
#rgb 转hsv
def rgb2hsv(r, g, b):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        h = (60 * ((g-b)/df) + 360) % 360
    elif mx == g:
        h = (60 * ((b-r)/df) + 120) % 360
    elif mx == b:
        h = (60 * ((r-g)/df) + 240) % 360
    if mx == 0:
        s = 0
    else:
        s = df/mx
    v = mx
    return (h, s, v)

def get_dominant_color(image):
    print(image.shape)
    px=image[int(image.shape[0]/2),int(image.shape[1]/2)]
    dominant_color = (px[2],px[1],px[0])
    return dominant_color
def judgecolor(h,s,v):
    h=h/360
    if v<0.25:
        c='black'
    elif v>0.75 and s<0.2:
         c='white'
    else:
        if h<1/18 or h>=23/24:
            c='red'
        if h>=1/18 and h<=3/24:
            c='orange'
        if h>3/24 and h<=5/24:
            c='yellow'
        if h>5/24 and h<=10/24:
            c='green'
        if h>10/24 and h<=15/24:
            c='cyan'
        if h>15/24 and h<9/12:
            c='blue'
        if h>=9/12 and h<10/12:
            c='purple'
        if h>=10/12 and h<23/24 :
            c='pink'
    return c

if __name__ == "__main__":
    path ='C:/Users/DELL/Desktop/hhh/2/'
    fp = open('file_color.txt', 'w')
    for filename in os.listdir(path):
        print(path + filename)
        image=cv.imread(path + filename)
        (r,g,b) = get_dominant_color(image)
        (h, s, v) = rgb2hsv(r, g, b)
        if abs(int(r) - int(g))<20 and abs(int(g) - int(b))<20:
            if r >= 200:
                color = 'white'
            if r < 50:
                color = 'black'
            if r >= 50 and r < 200:
                color = 'gray'
        # hsv判断彩色图颜色
        else:
            color = judgecolor(h, s, v)
        print('The color of ' + filename + ' is '+'h:'+str(h)+'s:'+str(s)+'v:'+str(v)+str(color)+ '\n')
        fp.write('The color of ' + filename + ' is ' + str(color) + '\n')
        # print("This file format is not support")
    fp.close()